package com.example.librarymanagementsystembackend.usermanagement.controller;


/**
 * 用户操作记录类 控制器
 */

import com.example.librarymanagementsystembackend.usermanagement.entity.UserAction;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 用户操作记录控制器，用于管理用户操作记录（如借阅、归还、登录等）
 */
import com.example.librarymanagementsystembackend.usermanagement.service.UserActionService;
import com.example.librarymanagementsystembackend.utils.InvalidRequestException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;

import org.springframework.web.bind.annotation.*;



@RestController
@RequestMapping("/userActions")
public class UserActionController {

    @Autowired
    private UserActionService userActionService;

    // 创建用户操作记录
    @PostMapping
    public int createUserAction(@RequestBody UserAction userAction) {
        return userActionService.createUserAction(userAction);
    }

    // 根据`主键`ID 获取操作记录
    @GetMapping("/{id}")
    public UserAction getUserActionById(@PathVariable Integer id) {
        return userActionService.getUserActionById(id);
    }

    // 根据`主键`ID删除操作记录
    @DeleteMapping("/{id}")
    public String deleteUserActionById(@PathVariable Integer id) {
        try {
            userActionService.deleteUserActionById(id);
            return "删除成功";
        } catch (InvalidRequestException e) {
            throw new InvalidRequestException("删除指定用户操作记录失败（" + e.getMessage() + "）");
        }
    }

    // 根据用户ID查询操作记录（按时间倒序）
    @GetMapping("/user/{userId}")
    public List<UserAction> getUserActionsByUserId(@PathVariable Integer userId) {
        return userActionService.getUserActionsByUserId(userId);
    }

    /**
     * 查询指定时间范围内的操作记录
     * 示例 http://localhost:8080/userActions/timeRange?startTime=2025-06-15T00:00:00&endTime=2025-06-16T16:08:38
     *
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @return 指定时间范围内的操作记录
     */
    @GetMapping("/timeRange")
    public List<UserAction> getUserActionsByTimeRange(
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime startTime,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime endTime)
    {
        return userActionService.getUserActionsByTimeRange(startTime, endTime);
    }
}